<template>
    <div class="app-container">
        <!-- 查询区域 -->
        <el-card class="search-card" v-show="showSearch">
            <el-form :model="queryParams">
                <el-row :gutter="20">
                    <el-col :span="8">
                        <el-form-item label="供应商名称">
                            <el-input v-model="queryParams.supplierName" placeholder="请输入供应商名称" clearable />
                        </el-form-item>
                    </el-col>
                    <el-col :span="8">
                        <el-form-item label="邮箱账号">
                            <el-input v-model="queryParams.emailAccount" placeholder="请输入邮箱账号" clearable />
                        </el-form-item>
                    </el-col>
                    <el-col :span="8">
                        <el-form-item label="激活状态">
                            <el-select v-model="queryParams.isActive" placeholder="请选择状态" clearable>
                                <el-option label="全部" value="" />
                                <el-option label="已激活" :value="1" />
                                <el-option label="未激活" :value="0" />
                            </el-select>
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row :gutter="20" style="margin-top: 20px;">
                    <el-col :span="16">
                        <el-button type="primary" @click="handleQuery">查询</el-button>
                        <el-button @click="resetQuery">重置</el-button>
                    </el-col>
                </el-row>
            </el-form>
        </el-card>

        <!-- 操作按钮区域 -->
        <el-card class="operation-card">
            <el-row :gutter="10" class="mb8">
                <el-col :span="1.5">
                    <el-button type="primary" plain icon="Plus" @click="handleAdd">新增</el-button>
                </el-col>
                <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
            </el-row>

            <el-table v-loading="loading" :data="emailConfigList" @selection-change="handleSelectionChange"
                style="width: 100%">
                <!-- <el-table-column type="selection" width="55" align="center" /> -->
                <!-- <el-table-column prop="emailConfigId" label="配置ID" align="center" /> -->
                <el-table-column type="index" label="序号" width="55" align="center" />

                <el-table-column prop="supplierName" label="供应商名称" align="center" />
                <el-table-column prop="emailAccount" label="邮箱账号" align="center" />
                <el-table-column prop="smtpServer" label="SMTP服务器" align="center" />
                <el-table-column prop="smtpPort" label="SMTP端口" align="center" />
                <el-table-column prop="isEnabled" label="加密状态" align="center">
                    <template #default="{ row }">
                        <el-tag :type="row.isEnabled === 1 ? 'success' : 'info'">
                            {{ row.isEnabled === 1 ? '已启用' : '未启用' }}
                        </el-tag>
                    </template>
                </el-table-column>
                <el-table-column prop="isActive" label="激活状态" align="center">
                    <template #default="{ row }">
                        <el-tag :type="row.isActive === 1 ? 'success' : 'danger'">
                            {{ row.isActive === 1 ? '已激活' : '未激活' }}
                        </el-tag>
                    </template>
                </el-table-column>
                <el-table-column label="操作" align="center" width="220">
                    <template #default="{ row }">
                        <el-button type="text" icon="Edit" @click="handleEdit(row)">编辑</el-button>
                        <el-button type="text" icon="Help" @click="handleTest(row)">测试</el-button>
                        <el-button type="text" icon="Delete" @click="handleDelete(row)">删除</el-button>
                    </template>
                </el-table-column>
            </el-table>

            <!-- 分页 -->
            <div class="pagination">
                <el-pagination v-model:current-page="queryParams.pageNum" v-model:page-size="queryParams.pageSize"
                    :total="total" :page-sizes="[10, 20, 50, 100]" layout="total, sizes, prev, pager, next, jumper"
                    @size-change="handleQuery" @current-change="handleQuery" />
            </div>
        </el-card>

        <!-- 新增/编辑对话框 -->
        <el-dialog v-model="dialog.visible" :title="dialog.title" width="600px" @closed="resetForm">
            <el-form ref="emailConfigForm" :model="form" :rules="rules" label-width="120px">
                <el-form-item label="配置ID" prop="emailConfigId" v-if="dialog.isEdit">
                    <el-input v-model="form.emailConfigId" disabled />
                </el-form-item>
                <el-form-item label="供应商" prop="supplierId">
                    <el-select v-model="form.supplierId" placeholder="请选择供应商" filterable clearable>
                        <el-option v-for="item in supplierOptions" :key="item.id" :label="item.name" :value="item.id" />
                    </el-select>
                </el-form-item>
                <el-form-item label="邮箱账号" prop="emailAccount">
                    <el-input v-model="form.emailAccount" placeholder="请输入邮箱账号" />
                </el-form-item>
                <el-form-item label="SMTP服务器" prop="smtpServer">
                    <el-input v-model="form.smtpServer" placeholder="请输入SMTP服务器地址" />
                </el-form-item>
                <el-form-item label="SMTP端口" prop="smtpPort">
                    <el-input-number v-model="form.smtpPort" :min="1" :max="65535" placeholder="请输入SMTP端口" />
                </el-form-item>
                <el-form-item label="SMTP用户名" prop="smtpUsername">
                    <el-input v-model="form.smtpUsername" placeholder="请输入SMTP用户名" />
                </el-form-item>
                <el-form-item label="SMTP密码" prop="smtpPassword">
                    <el-input v-model="form.smtpPassword" type="password" placeholder="请输入SMTP密码" show-password />
                </el-form-item>
                <el-form-item label="校验用户" prop="checkUser">
                    <el-input v-model="form.checkUser" placeholder="请输入校验用户" />
                </el-form-item>
                <el-form-item label="启用加密" prop="isEnabled">
                    <el-switch v-model="form.isEnabled" :active-value="1" :inactive-value="0" />
                </el-form-item>
                <el-form-item label="激活状态" prop="isActive">
                    <el-switch v-model="form.isActive" :active-value="1" :inactive-value="0" />
                </el-form-item>
            </el-form>
            <template #footer>
                <el-button @click="dialog.visible = false">取消</el-button>
                <el-button type="primary" @click="submitForm">确定</el-button>
            </template>
        </el-dialog>

        <!-- 测试邮件对话框 -->
        <el-dialog v-model="testDialog.visible" title="测试邮件发送" width="500px">
            <el-form ref="testFormRef" :model="testForm" :rules="testRules" label-width="100px">
                <el-form-item label="收件人" prop="sendTo">
                    <el-input v-model="testForm.sendTo" placeholder="请输入收件人邮箱" />
                </el-form-item>
                <el-form-item label="邮件主题" prop="subject">
                    <el-input v-model="testForm.subject" placeholder="请输入邮件主题" />
                </el-form-item>
                <el-form-item label="邮件内容" prop="text">
                    <el-input v-model="testForm.text" type="textarea" :rows="4" placeholder="请输入邮件内容" />
                </el-form-item>
            </el-form>
            <template #footer>
                <el-button @click="testDialog.visible = false">取消</el-button>
                <el-button type="primary" @click="submitTest">发送测试</el-button>
            </template>
        </el-dialog>
    </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Plus, Download, Delete } from '@element-plus/icons-vue'
import {
    listEmailConfig,
    getEmailConfig,
    addEmailConfig,
    updateEmailConfig,
    deleteEmailConfig,
    exportEmailConfig,
    sendTestEmail,
    getSupplierSelect
} from '@/api/basic/message/mail.js'

const showSearch = ref(true)
const emailConfigForm = ref(null);
// 数据状态
const loading = ref(false)
const emailConfigList = ref([])
const total = ref(0)
const selectedRows = ref([])
const supplierOptions = ref([]);
const testFormRef = ref()
// 查询参数
const queryParams = reactive({
    pageNum: 1,
    pageSize: 10,
    supplierName: '',
    emailAccount: '',
    isActive: ''
})

// 表单数据
const form = reactive({
    emailConfigId: undefined,
    supplierId: '',
    emailAccount: '',
    smtpServer: '',
    smtpPort: 465,
    smtpUsername: '',
    smtpPassword: '',
    checkUser: '',
    isEnabled: 1,
    isActive: 1
})

// 测试表单数据
const testForm = reactive({
    emailConfigId: undefined,
    sendTo: '',
    subject: '测试邮件',
    text: '这是一封测试邮件，用于验证SMTP配置是否正确'
})

// 对话框状态
const dialog = reactive({
    visible: false,
    title: '',
    isEdit: false
})

const testDialog = reactive({
    visible: false
})

// 表单验证规则
const rules = reactive({
    supplierId: [
        { required: true, message: '请选择供应商', trigger: 'change' }
    ],
    emailAccount: [
        { required: true, message: '请输入邮箱账号', trigger: 'blur' },
        { type: 'email', message: '请输入正确的邮箱格式', trigger: 'blur' }
    ],
    smtpServer: [
        { required: true, message: '请输入SMTP服务器地址', trigger: 'blur' }
    ],
    smtpPort: [
        { required: true, message: '请输入SMTP端口', trigger: 'blur' }
    ],
    smtpUsername: [
        { required: true, message: '请输入SMTP用户名', trigger: 'blur' }
    ],
    smtpPassword: [
        { required: true, message: '请输入SMTP密码', trigger: 'blur' }
    ],
    // checkUser: [
    //     { required: true, message: '请输入校验用户', trigger: 'blur' }
    // ]
})

const testRules = reactive({
    sendTo: [
        { required: true, message: '请输入收件人邮箱', trigger: 'blur' },
        { type: 'email', message: '请输入正确的邮箱格式', trigger: 'blur' }
    ],
    subject: [
        { required: true, message: '请输入邮件主题', trigger: 'blur' }
    ],
    text: [
        { required: true, message: '请输入邮件内容', trigger: 'blur' }
    ]
})

// 获取邮箱配置列表
const getList = async () => {
    loading.value = true
    try {
        const res = await listEmailConfig(queryParams)
        emailConfigList.value = res.rows || [];
        total.value = res.total || 0;
    } catch (error) {
        console.error('获取邮箱配置列表失败:', error)
        ElMessage.error('获取邮箱配置列表失败')
    } finally {
        loading.value = false
    }
}

// 查询处理
const handleQuery = () => {
    queryParams.pageNum = 1
    getList()
}

// 重置查询
const resetQuery = () => {
    queryParams.pageNum = 1
    queryParams.supplierName = ''
    queryParams.emailAccount = ''
    queryParams.isActive = ''
    getList()
}

// 多选处理
const handleSelectionChange = (selection) => {
    selectedRows.value = selection.map(item => item.emailConfigId)
}

// 新增配置
const handleAdd = () => {
    dialog.visible = true
    dialog.title = '新增邮箱配置'
    dialog.isEdit = false
}

// 编辑配置
const handleEdit = async (row) => {
    try {
        const res = await getEmailConfig(row.emailConfigId)
        Object.assign(form, res.data)
        dialog.visible = true
        dialog.title = '编辑邮箱配置'
        dialog.isEdit = true
    } catch (error) {
        console.error('获取邮箱配置详情失败:', error)
        ElMessage.error('获取邮箱配置详情失败')
    }
}

// 测试配置
const handleTest = (row) => {
    testForm.emailConfigId = row.emailConfigId
    testDialog.visible = true
}

// 提交测试
const submitTest = async () => {
    await testFormRef.value.validate(async (valid, fields) => {
        if (valid) {
            try {
                await sendTestEmail(testForm)
                ElMessage.success('测试邮件发送成功')
                testDialog.visible = false
            } catch (error) {
                console.error('测试邮件发送失败:', error)
                ElMessage.error('测试邮件发送失败')
            }
        }

    })

}

// 删除配置
const handleDelete = (row) => {
    ElMessageBox.confirm('确认删除该邮箱配置吗?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
    }).then(async () => {
        try {
            await deleteEmailConfig(row.emailConfigId)
            ElMessage.success('删除成功')
            getList()
        } catch (error) {
            console.error('删除失败:', error)
            ElMessage.error('删除失败')
        }
    }).catch(() => { })
}

// 批量删除
const handleBatchDelete = () => {
    if (selectedRows.value.length === 0) {
        ElMessage.warning('请至少选择一条记录')
        return
    }

    ElMessageBox.confirm(`确认删除选中的${selectedRows.value.length}条记录吗?`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
    }).then(async () => {
        try {
            await deleteEmailConfig(selectedRows.value.join(','))
            ElMessage.success('批量删除成功')
            getList()
        } catch (error) {
            console.error('批量删除失败:', error)
            ElMessage.error('批量删除失败')
        }
    }).catch(() => { })
}

// 导出Excel
const handleExport = async () => {
    try {
        await exportEmailConfig(queryParams)
        ElMessage.success('导出成功')
    } catch (error) {
        console.error('导出失败:', error)
        ElMessage.error('导出失败')
    }
}

// 重置表单
const resetForm = () => {
    Object.assign(form, {
        emailConfigId: undefined,
        supplierId: '',
        emailAccount: '',
        smtpServer: '',
        smtpPort: 465,
        smtpUsername: '',
        smtpPassword: '',
        checkUser: '',
        isEnabled: 1,
        isActive: 1
    })
}

// 提交表单
const submitForm = async () => {
    await emailConfigForm.value.validate(async (valid, fields) => {
        if (valid) {
            try {
                if (dialog.isEdit) {
                    await updateEmailConfig(form)
                    ElMessage.success('修改成功')
                } else {
                    await addEmailConfig(form)
                    ElMessage.success('新增成功')
                }
                dialog.visible = false
                getList()
            } catch (error) {
                console.error('操作失败:', error)
                ElMessage.error('操作失败')
            }
        } else {
            console.log('error submit!', fields)
        }
    })
}

getSupplierSelect().then((response) => {
    console.log(response);

    supplierOptions.value = response.data;
})

// 初始化
getList()
</script>

<style scoped>
.search-card {
    margin-bottom: 20px;
}

.operation-card {
    margin-bottom: 20px;
}

.operation-buttons {
    display: flex;
    gap: 10px;
}

.pagination {
    margin-top: 20px;
    text-align: right;
}
</style>